globalThis.__dirname = __dirname

globalThis.preloadInit = () => {
  window.jQuery = window.$ = require('jquery')
}

globalThis.electron = require('electron');
globalThis.path = require('path')
globalThis.fs = require('fs')
globalThis.os = require('os')
globalThis.ip = require('ip')
globalThis.navigator.clipboard = electron.clipboard

globalThis.getWebviewContents = function(webview) {
  return globalThis.electron.remote.webContents.fromId(webview.getWebContentsId())
}

globalThis.getWebviewHtml = function(webview, window) {
  return new Promise(function(resolve) {
    let webContents = globalThis.getWebviewContents(webview)

    const webviewInjectScript = `

        function css() {
          var sheets = document.styleSheets, ret = [];
          for (let i in sheets) {
            if (sheets[i].ownerNode && sheets[i].ownerNode.id.startsWith('cssobj_')) {
              var rules = sheets[i].rules || sheets[i].cssRules;
              for (let r in rules) {
                ret.push(rules[r].cssText);
              }
            }
          }
          return ret.filter(v => v);
        }

        let cssArr = css()
        console.log('sdsds')

        var data = {
          title: document.title,
          url: window.location.href,
          html: document.documentElement.outerHTML,
          css: cssArr,
          ver: '1.0'
        };

        function respond(event) {
          event.source.postMessage(data, '*');
        }

        window.addEventListener("message", respond, false);
    `;

    webContents.executeJavaScript(webviewInjectScript);
    webview.contentWindow.postMessage("Send me your data!", "*");
    window.addEventListener("message", receiveHandshake, false); // Listen for response
    function receiveHandshake(event) {
      // Data is accessible as event.data.*
      // This is the custom object that was injected during contentload()
      // i.e. event.data.title, event.data.url
      console.log(event.data)
      window.removeEventListener("message", receiveHandshake);
      resolve(event.data)
    }
  })
}

const { parseComponent } = require('vue-sfc-parser')
globalThis.parseVue = function(code) {
  const res = parseComponent(code)
  console.log(res)
  let ret = {
    html: '',
    js: '',
    css: ''
  }
  if (res.template) {
    ret.html = res.template.content
  }
  if (res.script) {
    ret.js = res.script.content
  }
  if (Array.isArray(res.styles) && res.styles.length > 0) {
    ret.css = res.styles[0].content
  }
  if (res.customBlocks) {
    res.customBlocks.forEach(customBlock => {
      ret[customBlock.type] = customBlock.content
    })
  }
  return ret
}

globalThis.requireFile = function(folderPath, filePath) {
  // console.log(folderPath)
  let p = path.join(folderPath, filePath)
  return {
    fileStr:  globalThis.fs.readFileSync(p).toString(),
    path: p.toString()
  }
};

const babel = require('@babel/core');
globalThis.transformJs = (data, cb) => {
  babel.transform(
    data,
    {
      "presets": [
        [
          "@babel/preset-env",
          {
            "useBuiltIns": "entry"
          }
        ]
      ]
    },
    function(e, result) {
      if (e) {
        console.log(e)
        return
      }
      cb(result.code)
    }
  );
}

globalThis.transformCssObj = (data, cb) => {
  babel.transform(
    data,
    {
      "plugins": ["transform-cssobj"]
    },
    function(e, result) {
      if (e) {
        console.log(e)
        return
      }
      cb(result.code)
    }
  );
}

globalThis.transformJsx = (data, cb) => {
  let _data = data.replace(/(<img("[^"]*"|[^\/">])*)>/gi, "$1/>")
  babel.transform(
    _data,
    {
      plugins: [ '@babel/plugin-transform-react-jsx' ],
    },
    function(e, result) {
      if (e) {
        console.log(e)
        return
      }
      cb(result.code)
    }
  );
}

const sass = require('sass');
const postcss = require('postcss')
const autoprefixer = require('autoprefixer')
globalThis.transformStyle = (css, cb) => {
  sass.render({
    data: css,
  }, function(err, sassresult) {
    postcss({
      plugins: [
        autoprefixer({
          browsers:  [
            '> 1%',
            'ie >= 9',
            'edge >= 15',
            'ie_mob >= 10',
            'ff >= 45',
            'chrome >= 45',
            'opera >= 23',
            'ios >= 9',
            'android >= 4',
            'bb >= 10'
          ]
        })
      ]
    }).process(sassresult.css).then(result => {
      cb(result.css)
    })
  });
}

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {

})